package at.fhj.itm11.forum.controller;

import java.util.Date;

import javax.annotation.PostConstruct;
import javax.enterprise.inject.Model;
import javax.enterprise.inject.Produces;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import at.fhj.itm11.forum.beans.AuthenticationBean;
import at.fhj.itm11.forum.beans.TopicBean;
import at.fhj.itm11.forum.model.Topic;
import at.fhj.itm11.forum.model.User;
import at.fhj.itm11.forum.service.TopicRegistration;
import at.fhj.itm11.forum.util.ForumConstants;

@Model
public class TopicController {

	@Inject
	private TopicBean topicBean;
	
	@Inject
	private AuthenticationBean authBean;
	
	@Inject
	private TopicRegistration topicRegistration;
	 
	@Produces
	@Named
	private Topic newTopic;
	 
	@PostConstruct
	public void initNewTopic() {
		newTopic = new Topic();
		}
	 
	public void register() throws Exception {
		FacesContext context = FacesContext.getCurrentInstance();
		try {

			User author = (User) authBean.getSession().getAttribute(ForumConstants.SESSION_CURRENT_USER);
			
			// check is user is logged in
			if(author == null) {
				context.addMessage(null, new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Please log in first!",
						null));
			// check for empty title
			} else if(newTopic.getTitle() == null || "".equals(newTopic.getTitle())) {
					context.addMessage("reg:title", new FacesMessage(
							FacesMessage.SEVERITY_ERROR, "Creation failed", "Title must not be empty!"));
			} else if(newTopic.getDescription() == null || "".equals(newTopic.getDescription())) {
				context.addMessage("reg:description", new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Creation failed", "Description must not be empty!"));	
			} else {
				newTopic.setAuthor(author);
				newTopic.setDate(new Date());
				topicRegistration.register(newTopic);
				context.addMessage(null, new FacesMessage(
						FacesMessage.SEVERITY_INFO, "Topic creation successful!",
						"Creation successful"));
				topicBean.setCurrentTopic(newTopic);
			}
		} catch (Exception e) {
			String errorMessage = getRootErrorMessage(e);
			context.addMessage(null, new FacesMessage(
					FacesMessage.SEVERITY_ERROR, errorMessage,
					"Creation failed"));
		}
	}

	private String getRootErrorMessage(Exception e) {
		// Default to general error message that registration failed.
		String errorMessage = "Registration failed. See server log for more information";
		if (e == null) {
			// This shouldn't happen, but return the default messages
			return errorMessage;
		}

		// Start with the exception and recurse to find the root cause
		Throwable t = e;
		while (t != null) {
			// Get the message from the Throwable class instance
			errorMessage = t.getLocalizedMessage();
			t = t.getCause();
		}
		// This is the root cause message
		return errorMessage;
	}
}